const { chromium } = require("playwright")
const { spawn } = require('child_process')
const fs = require('fs')
const DBConnection = require("./databaseUtil.js")

conn = new DBConnection()

openBroswer = async () => {
    chromeArgs = ["--disable-infobars", "--disable-sync", "--bwsi", "--no-sandbox",
    "--start-maximized", "--disable-extensions", "--disable-java",
    "--disable-pinch", "--allow-insecure-websocket-from-https-origin",
    "--disable-web-security",
    "--disable-blink-features", "--disable-blink-features=AutomationControlled",
    "--disable-gpu", "--disable-software-rasterizer",
    "--disable-features=PreloadMediaEngagementData, MediaEngagementBypassAutoplayPolicies",
    "--ignore-certificate-errors", "--enable-quic", "--disable-client-side-phishing-detection",
    "--safebrowsing-disable-download-protection", "--allow-running-insecure-content",
    "--safebrowsing-disable-auto-update"]
    const browser = await chromium.launchPersistentContext('lzj',{
        headless: false,
        args: chromeArgs,
        viewport: null
    });
    browser.addInitScript("''(() => {window.$XMLHttpRequest = window.XMLHttpRequest;window.$XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;window.$XMLHttpRequestSend = window.XMLHttpRequest.prototype.send;window.$XMLHttpRequestSetRequestHeader = window.XMLHttpRequest.prototype.setRequestHeader;window.$Fetch = window.fetch;})()''")
    browser.setDefaultTimeout(10 * 60 * 1000)
    browser.setDefaultNavigationTimeout(10 * 60 * 1000)
    const page = await browser.newPage();
    await page.goto("https://shopee.sg");
    await page.pause()
    conn.query("select itemId,shopId from t_product ORDER BY RAND()", []).then(async res => {
        resObj = JSON.parse(JSON.stringify(res))
        for (index in resObj){
            try {
                let item = resObj[index];
                let url = `https://shopee.sg/product/${item.shopId}/${item.itemId}`;
                await gotoUrl(page, url);
                await page.mouse.wheel(0,600)
                while(page.url().indexOf("product") == -1){
                    await page.pause()
                    await dragVerify(page)
                }
            } catch (error) {
                console.log(error)
                continue
            }
        }
    })
}

dragVerify = async (page) => {
    await page.evaluate("for(var i=0; i <= 1000; i++){window.clearInterval(i);}")
    bgSrc = await page.locator('xpath=/html/body/div[1]/div/div[2]/div/div/div/div/div[2]/div[1]/div[1]/img').getAttribute('src')
    bgContext = bgSrc.split(",")
    var bgBuffer = Buffer.from(bgContext[1], 'base64')
    fs.writeFileSync('background.jpg', bgBuffer)

    silderSrc = await page.locator('xpath=/html/body/div[1]/div/div[2]/div/div/div/div/div[2]/div[1]/div[2]/img').getAttribute('src')
    silderContext = silderSrc.split(",")
    var silderBuffer = Buffer.from(silderContext[1], 'base64')
    fs.writeFileSync('silder.png', silderBuffer)

    const sildeVerifyProcess = spawn('python', ["./sildeVerify.py"])
    sildeVerifyProcess.stdout.on('data', function (data){
        var offset = data.toString();
        const dragVerifyProcess = spawn('python', ["./dragVerify.py", offset])
        dragVerifyProcess.stdout.on('end',async () => {
            if (page.url().indexOf("verify") != -1){
                if(page.url().indexOf("verify/traffic") != -1){
                    await page.locator('xpath=//*[@id="main"]/div/div[2]/div/div/div/div[3]/button').click()
                    await page.waitForLoadState()
                }
                await dragVerify(page)
                await page.waitForLoadState()
            }
        })
    });
}

gotoUrl = async (page, url) => {
    try {
        await page.goto(url, {timeout: 1 * 60 * 1000, waitUtil: "load"})
    } catch (error) {
        await gotoUrl(page, url)
    }
}

openBroswer()
